<?php


namespace app\admin\system\service;


use app\model\SysAdmin;
use app\model\SysMenu;
use app\model\SysRole;
use app\model\SysRoleMenu;
use think\db\exception\DbException;

class AdminService
{
    const SUPPER_PERMISSION = ["*"];


    /**
     * 判断登录人是否是超级管理员
     * @param $uid
     * @return bool
     * @throws DbException
     */
    static function isSuperAdmin($uid)
    {
        $role_ids = self::getRoleIdsByUid($uid);
        if (!$role_ids) {
            return false;
        }
        return self::isSuperAdminRole($role_ids);
    }

    static function getRoleIdsByUid($uid)
    {
        $data = SysAdmin::where([
            'id' => $uid
        ])->value("role_ids");
        if (!$data) {
            return [];
        }
        return explode(',', $data);
    }

    static function getRoleNames($uid)
    {
        $role_ids = self::getRoleIdsByUid($uid);
        if (!$role_ids) {
            return false;
        }
        return SysRole::where([
            ['roleId', 'in', $role_ids],
        ])
            ->column('roleName');
    }

    /**
     * 判断角色是否是超级角色
     * @param $role_ids
     * @return bool
     * @throws DbException
     */
    static function isSuperAdminRole($role_ids)
    {
        $count = SysRole::where([
            ['roleId', 'in', $role_ids],
            ['isSuperAdmin', '=', 1],
        ])
            ->count();
        return $count > 0;
    }

    /**
     * 获取可用权限集
     * @param $uid
     * @param array $menuType 菜单类型
     * @return array|string[]
     */
    static function getAuthority($uid, $menuType = [])
    {
        $data = SysAdmin::where([
            'id' => $uid
        ])->value("role_ids");
        if (!$data) {
            return [];
        }
        $role_ids = explode(',', $data);
        if (self::isSuperAdminRole($role_ids)) {
            return self::SUPPER_PERMISSION;
        }

        $query = SysMenu::alias('a')
            ->join(SysRoleMenu::getTable() . ' b', 'a.menuId=b.menu_id')
            ->where('b.role_id', 'in', $role_ids)
            ->order("a.sorted");
        if ($menuType) {
            $query->where('a.menuType', 'in', $menuType);
        }
        $data = $query
            ->column('a.auth');
        return $data;
    }

}